/*
Copyright (c) 2007, Arturo José Guédez Romero

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of Cultusoft nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.cultusoft.groovin.plugins.eclipse;

import com.cultusoft.groovin.log.GroovinLogger

class EclipseClasspathSetter {
	
	def projects

    def logger = new GroovinLogger(this)
	
	public void run() {
		setEclipseClasspath(projects)
	}
	
	private void setEclipseClasspathToSingleProject(def project, def eclipseClasspathsModified) {
		createFoldersIfNeeded(project);
		def eclipseProjectDir = project.directory
		
		File classpathFile = new File(eclipseProjectDir, ".classpath")

		StringBuffer classpathContent = new StringBuffer();
		
		if (eclipseClasspathsModified.contains(eclipseProjectDir) ) {
			loadBufferFromFile(classpathContent, classpathFile);
		} else {
			createBrandNewClasspathFile(classpathContent, classpathFile);
			eclipseClasspathsModified.add(eclipseProjectDir)
		}
		
		addSourceDirectories(classpathContent, project)
		
		for (resource in project.getResources()) {
			addResourceDirectory(classpathContent, resource, project);
		}
		
		List dependantProjectsAdded = new ArrayList();
		addAllReferecenesToDependant(classpathContent, project, project, dependantProjectsAdded)
		
		writeFile(classpathContent, classpathFile );
		logger.log(".classpath in " + project.getDirectory() + " updated")
	}
	
	private void setEclipseClasspath(def projects) {
		def eclipseClasspathsModified = new ArrayList()
		
		for (project in projects) {
			setEclipseClasspathToSingleProject(project, eclipseClasspathsModified)
		}

	}
	
	
	
	private void addAllReferecenesToDependant(def classpathContent, def currentProject, def rootProject, def dependantProjectsAdded) {
			
		if (dependantProjectsAdded.contains(currentProject)) {
			return
		}
		
		addReferencesToDependant(classpathContent, currentProject, rootProject)
		dependantProjectsAdded.add(currentProject);
		
		for (dependantProject in currentProject.getDependencies()) {
			addAllReferecenesToDependant(classpathContent, dependantProject, rootProject, dependantProjectsAdded)
		}
		
	}
	
	private void writeFile (StringBuffer buffer, File file ) {
		buffer.append("</classpath>\n");
		try {
	    	BufferedWriter out = new BufferedWriter(new FileWriter(file));
			out.write(buffer.toString());
			out.close();
		} catch (IOException e) {
		}
	}
	
	private void createFoldersIfNeeded(def project) {
		if (project.destinationDirectory != null) {
			File destinationTargetFolder = new File(project.destinationDirectory);
			if (!destinationTargetFolder.exists()) {
				destinationTargetFolder.mkdir();
			}
		}
		
		if (project.sourceDirectoriesPaths != null) {
			for (sourceDirectoryPath in project.sourceDirectoriesPaths) {
				File sourceFolder = new File(sourceDirectoryPath);
				if (!sourceFolder.exists()) {
					sourceFolder.mkdir();
				}
			}
		}
		if (project.resources != null) {
			for (resource in project.resources) {
				String relativeResourceDirectory = resource.substring(project.getDirectory().length());
				File resourceFolder = new File(resource);
				if (!resourceFolder.exists()) {
					resourceFolder.mkdir();
				}
			}
		}
	}
	
	private void addReferencesToDependant(def buffer, def dependantProject, def project) {
		String possibleClasspathEntry = null;
		if (dependantProject.getDirectory() != null) {
			if (dependantProject.getDirectory().equals(project.getDirectory())) {
				return;
			}
			// make dependency to Eclipse project
			String eclipseProjectName = File.separator + dependantProject.getDirectoryName()
			
			possibleClasspathEntry = "\t<classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"" + eclipseProjectName + "\"/>\n";
		}  else {
			// make dependency to jar from library
			possibleClasspathEntry = "\t<classpathentry kind=\"lib\" path=\"$dependantProject.packagingLocation\"/>\n";
		}
		appendUniqueStringToBuffer(buffer, possibleClasspathEntry);
	}
	
	private void addResourceDirectory(def buffer, def resource, def project) {
		String relativeResourceDirectory = resource.substring(project.getDirectory().length());
		
		if (relativeResourceDirectory.startsWith("/")) {
			relativeResourceDirectory = relativeResourceDirectory.substring(1);
		}
		String possibleClasspathEntry = "\t<classpathentry kind=\"src\" path=\"" + relativeResourceDirectory + "\"/>\n";
		
		appendUniqueStringToBuffer(buffer, possibleClasspathEntry);
	}
	
	def addSourceDirectories(def buffer, def project) {
		String relativeDestDirectory = project.getDestinationDirectory().substring(project.getDirectory().length());
		if (relativeDestDirectory.startsWith("/")) {
			relativeDestDirectory = relativeDestDirectory.substring(1);
		}
		
		if (project.getSourceDirectoriesPaths() == null) {
			return
		}

		for (sourceDirectoryPath in project.getSourceDirectoriesPaths()) {
			if (isRelativeSourceDirectory(sourceDirectoryPath,project.getDirectory())) {
				String  relativeSrcDirectory = sourceDirectoryPath.substring(project.getDirectory().length());
				if (relativeSrcDirectory.startsWith("/")) {
					relativeSrcDirectory = relativeSrcDirectory.substring(1);
				}
			
				String tentativeSourceEntry ="\t<classpathentry kind=\"src\" output=\"" + relativeDestDirectory +
				"\" path=\"" + relativeSrcDirectory +"\"/>\n";
				appendUniqueStringToBuffer(buffer, tentativeSourceEntry);
			}
		}
	}
	private boolean isRelativeSourceDirectory(def sourceDirectoryPath, def projectDirectory) {
		return sourceDirectoryPath.contains(projectDirectory)
	}
	
	private void createBrandNewClasspathFile(StringBuffer buffer, File file) {
		if (file.exists()) {
			file.delete();
		}
		file.createNewFile();
		
		buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		buffer.append("<classpath>\n");
		buffer.append("\t<classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n");
		buffer.append("\t<classpathentry kind=\"output\" path=\"bin\"/>\n");
	}
	
	private void loadBufferFromFile(StringBuffer buffer, File file){
		try {
	        BufferedReader reader = new BufferedReader(new FileReader(file));
	        String str;
	        while ((str = reader.readLine()) != null) {
	        	if (str.contains("</classpath>")) {
					break;				        		
	        	} else {
	        		buffer.append(str);
	        		buffer.append("\n");
	        	}
	        }
	        reader.close();
	    } catch (IOException e) {
	    }
	}
	
	private void appendUniqueStringToBuffer(StringBuffer buffer, String toAppend) {
		if (!buffer.toString().contains(toAppend)) {
			buffer.append(toAppend);
		}
	}
}
